package com.symaster.common.util;

import java.io.Reader;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author yinmiao
 * @date 2021-10-09 11:23
 */
public class PropertiesUtils {

    public static Map<String, String> loadProps(String path) {
        Map<String, String> stringStringMap = null;
        try {
            stringStringMap = loadProps(new FileInputStream(path));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return stringStringMap;
    }

    public static Map<String, String> loadProps(InputStream is) {
        HashMap<String, String> result = new HashMap<>();
        Properties properties = new Properties();
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(is, StandardCharsets.UTF_8);
            properties.load(isr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        for (String key : properties.stringPropertyNames()) {
            result.put(key, properties.getProperty(key));
        }

        return result;
    }

    public static Map<String, String> loadProps(Reader reader) {
        HashMap<String, String> result = new HashMap<>();
        Properties properties = new Properties();
        try {
            properties.load(reader);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        for (String key : properties.stringPropertyNames()) {
            result.put(key, properties.getProperty(key));
        }

        return result;
    }

    public static void saveProps(String path, Map<String, String> props) {
        File file = new File(path).getParentFile();
        if (file != null && !file.isDirectory() && !file.mkdirs()) {
            throw new RuntimeException(String.format("%s 不是可读文件", path));
        }

        OutputStreamWriter osw = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            osw = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
            Properties properties = new Properties();
            for (String key : props.keySet()) {
                properties.setProperty(key, props.get(key));
            }
            properties.store(osw, "Charset UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(fileOutputStream, osw);
        }

    }
}
